import fetch from 'node-fetch';
import {createLogger} from './Logger.js';
import {OPSConstant} from '../constant/OPSConstant.js';

/**
 * EasySearch 客户端，负责登录和检索日志
 */
export class EasySearchClient {
    /**
     * @param {string} username EasySearch 登录用户名
     * @param {string} password EasySearch 登录密码
     * @param {boolean} verbose 是否打印调试信息
     */
    constructor(username, password, verbose = false) {
        this.username = username;
        this.password = password;
        this.logger = createLogger('EasySearch');
        this.verbose = verbose;
        this.accessToken = null;
        this.expireAt = 0;
    }

    /**
     * 确保 token 可用，若已过期则重新登录
     * @returns {Promise<string>}
     */
    async ensureToken() {
        const now = Date.now();
        if (this.accessToken && now < this.expireAt - OPSConstant.EASY_SEARCH_TOKEN_REFRESH_GUARD) {
            return this.accessToken;
        }
        await this.login();
        return this.accessToken;
    }

    /**
     * 调用登录接口换取访问 token
     * @returns {Promise<void>}
     */
    async login() {
        if (!this.username || !this.password) {
            throw new Error('未配置 EasySearch 登录账号，请先在全局配置文件中填写 easysearch_username 与 easysearch_password');
        }
        const body = {
            userName: this.username,
            password: this.password,
            type: 'account'
        };
        const response = await fetch(OPSConstant.EASY_SEARCH_LOGIN_URL, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(body)
        });

        const text = await response.text();
        if (this.verbose) {
            this.logger.debug(`登录响应: status=${response.status} body=${text}`);
        }
        if (!response.ok) {
            throw new Error(`EasySearch 登录失败，HTTP 状态码 ${response.status}`);
        }
        let data;
        try {
            data = JSON.parse(text);
        } catch (error) {
            throw new Error(`EasySearch 登录响应解析失败: ${error.message}`);
        }
        if (!data?.access_token) {
            throw new Error('EasySearch 登录成功但是未返回 access_token，请检查账号权限');
        }
        this.accessToken = data.access_token;
        const expireInSeconds = typeof data.expire_in === 'number' ? data.expire_in : OPSConstant.EASY_SEARCH_TOKEN_TTL_FALLBACK;
        this.expireAt = Date.now() + expireInSeconds * 1000;
        if (this.verbose) {
            this.logger.debug(`登录成功，token 有效期 ${expireInSeconds} 秒`);
        }
    }

    /**
     * 调用 EasySearch 检索接口
     * @param {object} payload 请求体，包含 index 与 body
     * @returns {Promise<any>}
     */
    async search(payload) {
        if (!payload?.index || !payload?.body) {
            throw new Error('EasySearch 查询参数不完整，缺少 index 或 body');
        }
        const token = await this.ensureToken();
        const response = await fetch(OPSConstant.EASY_SEARCH_SEARCH_URL, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(payload)
        });
        const text = await response.text();
        if (this.verbose) {
            this.logger.debug(`查询响应: status=${response.status} body=${text}`);
        }
        if (!response.ok) {
            throw new Error(`EasySearch 查询失败，HTTP 状态码 ${response.status}`);
        }
        try {
            return JSON.parse(text);
        } catch (error) {
            throw new Error(`EasySearch 查询结果解析失败: ${error.message}`);
        }
    }
}
